package com.flow.asyncflow.core.utils.translate;

import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSONObject;
import com.flow.asyncflow.core.utils.http.HttpClientRequest;
import com.flow.asyncflow.core.utils.http.HttpClientResponse;
import com.flow.asyncflow.core.utils.http.HttpClientUtil;
import com.flow.asyncflow.core.utils.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class AsyncFlowTranslateUtil {


    /**
     * 百度翻译
     *
     * @param query 需要翻译的词
     * @return 结果
     */
    public static String baiDuTranslate(String query) {
        String result = "";
        String salt = UUID.randomUUID().toString();
        String appId = "xxxxx"; //百度APIkey,目前用的是lgq的
        String key = "xxxxxxx";
        Map<String, Object> req = new HashMap<>();
        req.put("q", query);
        req.put("from", "en");
        req.put("to", "zh");
        req.put("appid", appId);
        req.put("salt", salt);
        String sign = appId + query + salt + key;
        req.put("sign", DigestUtils.md5DigestAsHex(sign.getBytes()).toLowerCase());
        HttpClientRequest httpClientRequest = new HttpClientRequest();
        httpClientRequest.setParameter(req);
        httpClientRequest.setUrl("https://fanyi-api.baidu.com/api/trans/vip/translate");
        httpClientRequest.setHttpMethod(HttpMethod.PostForm);
        HttpClientResponse HttpClientResponse;
        HttpClientResponse = HttpClientUtil.httpResponse(httpClientRequest);
        JSONObject resultJsonObj = JSONObject.parseObject(HttpClientResponse.getBody());
        if (resultJsonObj.containsKey("trans_result") && resultJsonObj.getJSONArray("trans_result").size() > 0) {
            String dst = JSONObject.parseObject(resultJsonObj.getJSONArray("trans_result").get(0).toString()).getString("dst");
            result = dst;
        }
        return result;
    }


    /**
     * @param string
     * @return 转换之后的内容
     * @Title: unicodeDecode
     * @Description: unicode解码 将Unicode的编码转换为中文
     */
    public static String unicodeDecode(String string) {
        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
        Matcher matcher = pattern.matcher(string);
        char ch;
        while (matcher.find()) {
            ch = (char) Integer.parseInt(matcher.group(2), 16);
            string = string.replace(matcher.group(1), ch + "");
        }
        return string;
    }
}
